// LogRecordActivity.java
package no.nordicsemi.android.nrfmesh;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import no.nordicsemi.android.nrfmesh.database.AppDatabase;
import no.nordicsemi.android.nrfmesh.database.entity.LogRecord;
import no.nordicsemi.android.nrfmesh.viewmodels.LogRecordViewModel;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class LogRecordActivity extends AppCompatActivity {
    private static final String TAG = "LogRecordActivity";
    private LogRecordViewModel viewModel;
    private LogRecordAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_log_record);

        // 添加调试代码，直接查询数据库
        new Thread(() -> {
            try {
                List<LogRecord> records = AppDatabase.getInstance(LogRecordActivity.this)
                        .logRecordDao()
                        .getAllLogRecordsSync();
                Log.d(TAG, "直接查询数据库结果，记录数: " + records.size());
                for (LogRecord record : records) {
                    Log.d(TAG, "数据库记录详情 - ID: " + record.id +
                            ", 开始时间: " + record.startTime +
                            ", 档位: " + record.gear);
                }
            } catch (Exception e) {
                Log.e(TAG, "查询数据库失败", e);
            }
        }).start();

        RecyclerView recyclerView = findViewById(R.id.recycler_view_logs);
        if (recyclerView != null) {
            recyclerView.setLayoutManager(new LinearLayoutManager(this));
            adapter = new LogRecordAdapter(logRecord -> {
                // 点击事件处理，跳转到详情页面
                Intent intent = new Intent(LogRecordActivity.this, LogRecordDetailActivity.class);
                intent.putExtra(LogRecordDetailActivity.EXTRA_LOG_RECORD_ID, logRecord.id);
                startActivity(intent);
            });
            recyclerView.setAdapter(adapter);

            viewModel = new ViewModelProvider(this).get(LogRecordViewModel.class);
            viewModel.getLogRecords().observe(this, logRecords -> {
                Log.d(TAG, "观察到日志记录变化，记录数: " + (logRecords != null ? logRecords.size() : 0));
                if (logRecords != null) {
                    // 打印调试信息
                    for (LogRecord record : logRecords) {
                        Log.d(TAG, "记录详情 - ID: " + record.id + ", 开始时间: " + record.startTime);
                    }
                    adapter.submitList(logRecords);
                } else {
                    Log.d(TAG, "观察到的日志记录为 null");
                }
            });
        } else {
            Log.e(TAG, "RecyclerView 为 null");
        }
    }

    // 适配器实现
    private static class LogRecordAdapter extends RecyclerView.Adapter<LogRecordViewHolder> {
        private List<LogRecord> logRecords = new ArrayList<>();
        private OnItemClickListener listener;

        public interface OnItemClickListener {
            void onItemClick(LogRecord logRecord);
        }

        public LogRecordAdapter(OnItemClickListener listener) {
            this.listener = listener;
        }

        public void submitList(List<LogRecord> logRecords) {
            this.logRecords = logRecords != null ? logRecords : new ArrayList<>();
            notifyDataSetChanged();
        }

        @Override
        public LogRecordViewHolder onCreateViewHolder(android.view.ViewGroup parent, int viewType) {
            android.view.View view = android.view.LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_log_record, parent, false);
            return new LogRecordViewHolder(view);
        }

        @Override
        public void onBindViewHolder(LogRecordViewHolder holder, int position) {
            if (position < logRecords.size()) {
                LogRecord record = logRecords.get(position);
                holder.bind(record);

                // 原来的跳转逻辑
                holder.itemView.setOnClickListener(v -> {
                    if (listener != null) {
                        listener.onItemClick(record);
                    }
                });

                // 新增删除逻辑 - 先弹出确认对话框
                holder.btnDelete.setOnClickListener(v -> {
                    new android.app.AlertDialog.Builder(holder.itemView.getContext())
                            .setTitle("确认删除")
                            .setMessage("确定要删除这条使用记录吗？")
                            .setPositiveButton("确定", (dialog, which) -> {
                                new Thread(() -> {
                                    AppDatabase.getInstance(holder.itemView.getContext())
                                            .logRecordDao()
                                            .deleteLogRecord(record);
                                    Log.d(TAG, "删除 LogRecord ID=" + record.id);
                                }).start();
                            })
                            .setNegativeButton("取消", (dialog, which) -> dialog.dismiss())
                            .show();
                });
            }
        }

        @Override
        public int getItemCount() {
            return logRecords.size();
        }
    }

    private static class LogRecordViewHolder extends RecyclerView.ViewHolder {
        private TextView tvStartTime, tvDuration, tvGear, tvTotalTime, tvSegments, tvConfigName;
        private TextView btnDelete; // ❌ 删除按钮

        public LogRecordViewHolder(android.view.View itemView) {
            super(itemView);
            tvStartTime = itemView.findViewById(R.id.tv_start_time);
            tvDuration = itemView.findViewById(R.id.tv_duration);
            tvGear = itemView.findViewById(R.id.tv_gear);
            tvTotalTime = itemView.findViewById(R.id.tv_total_time);
            tvSegments = itemView.findViewById(R.id.tv_segments);
            tvConfigName = itemView.findViewById(R.id.tv_config_name);
            btnDelete = itemView.findViewById(R.id.btn_delete); // 绑定删除按钮
        }

        public void bind(LogRecord record) {
            if (record.startTime != null) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
                tvStartTime.setText(sdf.format(record.startTime));
            } else {
                tvStartTime.setText("未知");
            }

            if (record.duration > 0) {
                long seconds = record.duration / 1000;
                long minutes = seconds / 60;
                long remainingSeconds = seconds % 60;
                tvDuration.setText(String.format("%02d:%02d", minutes, remainingSeconds));
            } else {
                tvDuration.setText("00:00");
            }

            tvGear.setText(String.valueOf(record.gear));
            tvTotalTime.setText(record.totalTime + " 分钟");
            tvSegments.setText(String.valueOf(record.totalSegments));
            
            // 显示配置名称 - 修复显示问题
            if (record.configName != null && !record.configName.trim().isEmpty()) {
                tvConfigName.setText(record.configName);
            } else {
                tvConfigName.setText("未命名");
            }
            }
        }
    }


